<template>
    <a-card>
        <a-space style="width: 100%" direction="vertical">
            <a-flex justify="space-between">
                <a-breadcrumb style="margin-left: 6px;font-size: 16px;">
                    <a-breadcrumb-item v-for="path in filepath"
                                       style="cursor: pointer"
                                       @click="handleFilePathClick(path)"
                    >
                        {{ path }}
                    </a-breadcrumb-item>
                </a-breadcrumb>
                <a-button type="primary"
                          @click="batchDownloadExcel"

                >
                    <template #icon>
                        <DownloadOutlined />
                    </template>
                    批量下载Excel
                </a-button>
                <a-button type="primary"
                          @click="batchDownloadJSON"

                >
                    <template #icon>
                        <DownloadOutlined />
                    </template>
                    批量下载JSON
                </a-button>
                <a-button type="primary"
                          @click="getExcelList"

                >
                    <template #icon>
                        <ReloadOutlined />
                    </template>
                    刷新
                </a-button>
            </a-flex>

            <a-table
                    :columns="columns"
                    :data-source="data"
                    :loading="loading"
                    :pagination="false"
                    :row-selection="rowSelection"
                    row-key="name"
            >
                <template #bodyCell="{ column, record }">
                    <template v-if="column.dataIndex === 'name'">
                        <a-button type="link">
                            <template #icon>
                                <FolderOutlined v-show="record.type ==='directory'"/>
                                <FileExcelOutlined  v-show="record.type ==='excel'"/>
                            </template>
                            {{ record.name }}</a-button>
                    </template>
                </template>

            </a-table>
        </a-space>

    </a-card>
</template>

<script setup>
import {ref} from 'vue'
import {getAction, postAction} from '@/request/request'
import {adminUrl} from '@/api/api'
import {ReloadOutlined,FolderOutlined,FileExcelOutlined,DownloadOutlined} from '@ant-design/icons-vue'
import {message, Modal} from "ant-design-vue";

const filepath = ref(['User'])
const handleFilePathClick = (path) => {
    const index = filepath.value.indexOf(path)
    if (index !== -1) {
        filepath.value.splice(index + 1)
    }
    getExcelList()
}
const columns = ref([
    {
        title: '序号',
        customRender : (value) => {
            const {index} = value
            return index + 1
        },
        width: 80
    },
    {
        title: '文件名',
        dataIndex: 'name',
        customCell: (record,index,column) => {
            return {
                onClick: (event) => {
                    const {name,type,parentPath} = record
                    if (type === 'directory') {
                        filepath.value.push(name)
                        getExcelList()
                    }else if (type === 'excel'){
                        Modal.confirm({
                            title: '下载文件',
                            content: '确定要下载文件吗?',
                            okText: '确定',
                            cancelText: '取消',
                            onOk: () => {
                                // 执行打开文件操作
                                DownloadFile(name,parentPath)
                            }
                        })
                    }

                },
                onMouseenter: (event) => {
                    event.target.style.cursor = 'pointer'
                },
            }
        }
    },
    {
        title: '类型',
        dataIndex: 'type',
        customRender: (value) => {
            const {text} = value
            switch (text){
                case 'directory':
                    return '文件夹'
                case 'excel':
                    return 'Excel文件'
            }
        }
    },
])
const selectedRowKeys = ref([])
const rowSelection = {
    type: 'checkbox',
    onChange: (keys, selectedRows) => {
        selectedRowKeys.value = keys
    },
}

const DownloadFile = (filename,parentPath) => {
    postAction(adminUrl.downloadFile, {
        path: filepath.value.join(',').replace("User,", ''),
        filename: filename,
        parentPath: parentPath
    },{
        responseType: 'blob'
    }).then(res => {
        const blob = new Blob([res], {
            // type: res.headers['content-type'] // 自动识别文件类型
        });
        const downloadUrl = window.URL.createObjectURL(blob);

        // 3. 动态创建<a>标签并触发点击
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = filename; // 设置下载文件名
        document.body.appendChild(link);
        link.click();

        // 4. 清理资源
        document.body.removeChild(link);
        window.URL.revokeObjectURL(downloadUrl);
    }).catch(error => {
        console.error('下载失败:', error);
    })
}

const batchDownloadExcel = () => {
    if (selectedRowKeys.value.length === 0) {
        message.error('请选择要下载的文件')
        return
    }
    if (selectedRowKeys.value.some(item => item.endsWith('.xlsx') === false)) {
        message.error('请选择Excel文件')
        return
    }

    postAction(adminUrl.downloadMultipleFiles,{
        path: filepath.value.join(',').replace("User,", ''),
        fileNames: selectedRowKeys.value.join(',')
    },{
        responseType: 'blob'
    }).then(res =>{
        const blob = new Blob([res], {
            // type: res.headers['content-type'] // 自动识别文件类型
        });
        const downloadUrl = window.URL.createObjectURL(blob);

        // 3. 动态创建<a>标签并触发点击
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = `${filepath.value.join('_')}.zip`; // 设置下载文件名
        document.body.appendChild(link);
        link.click();

        // 4. 清理资源
        document.body.removeChild(link);
        window.URL.revokeObjectURL(downloadUrl);
    })
}

const batchDownloadJSON = () => {
    if (selectedRowKeys.value.length === 0) {
        message.error('请选择要下载的文件')
        return
    }
    if (selectedRowKeys.value.some(item => item.endsWith('.xlsx') === false)) {
        message.error('请选择Excel文件')
        return
    }

    postAction(adminUrl.batchDownloadJSON,{
        path: filepath.value.join(',').replace("User,", ''),
        fileNames: selectedRowKeys.value.join(',')
    },{
        responseType: 'blob'
    }).then(res =>{
        const blob = new Blob([res], {
            // type: res.headers['content-type'] // 自动识别文件类型
        });
        const downloadUrl = window.URL.createObjectURL(blob);

        // 3. 动态创建<a>标签并触发点击
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = `${filepath.value.join('_')}.zip`; // 设置下载文件名
        document.body.appendChild(link);
        link.click();

        // 4. 清理资源
        document.body.removeChild(link);
        window.URL.revokeObjectURL(downloadUrl);
    })
}

const data = ref([])
const loading = ref(false)
const getExcelList = () => {
    loading.value = true
    // 获取excel列表
    postAction(adminUrl.getExcelFileList, {
        path: filepath.value.join(','),
        username:filepath.value[1]?filepath.value[1]:'',
    }).then(res => {
        data.value = res.data
        selectedRowKeys.value = []
    }).finally(() => {
        loading.value = false
    })
}
defineExpose({
    getExcelList
})
</script>

<style scoped>

</style>
